//1.引入router
var express = require('express');
var router = express.Router();

//2.引入mongoose的数据模块
var mongoose = require('mongoose');
var Good = require('../models/goods');
var User = require('../models/user');
require('../util/util.js')

router.get('/', function (req, res, next) {
  User.findOne({ name: "zhangangs" }, function (err, user) {
    console.log(user);
    res.render('index', { title: 'Express', user: user });
  });
});
router.post("/login",function (req,res,next) {
  var param = {
    userName : req.body.userName,
    userPwd : req.body.userPwd
  }
  User.findOne(param,function (err,doc) {
    if(err){
      res.json({
        status:"1",
        msg:err.message
      });
    }else{
      if(doc){
        res.cookie("userId",doc.userId,{
          path:"/",
          maxAge:1000*60*60
        });
        res.cookie("userName", doc.userName, {
          path: "/",
          maxAge: 1000 * 60 * 60
        });
        res.json({
          status:'0',
          msg:'',
          result:{
            userName:doc.userName,
            userPwd:doc.userPwd
          }
        })
      }else{
        res.json({
          status: '1',
          msg: '无此用户',
          result: {
            
          }
        })
      }
    }
  })
})
router.post("/logout",function (req,res,next) {
  res.cookie("userId", "", {
    path: "/",
    maxAge: -1
  });
  res.cookie("userName", "", {
    path: "/",
    maxAge: -1
  });
  res.json({
    status: "0",
    msg: '',
    result: ''
  })
})
router.post("/cartList",function (req,res,next) {
  let userId = req.cookies.userId;
  User.findOne({userId:userId},function (err,doc) {
    if(err){
      res.json({
          status:"1",
          msg:err.message,
          result:""
      })
    }else{
      if(doc){
        res.json({
          status: "0",
          msg: "",
          result: doc.cartList
        })
      }
    }
  })
})
router.post("/editCart",function (req,res,next) {
  let productId = req.body.productId;
  let checked = req.body.checked;
  let productNum = parseInt(req.body.productNum);
  let userId = req.cookies.userId;
  User.update({
    "userId":userId,
    "cartList.productid": productId
  }, {
    "cartList.$.productNum": productNum,
    "cartList.$.checked": checked
  },function (err,doc) {
    if(err){
      res.json({
        status:"1",
        msg:err.message
      })
    }else{
      if(doc){
        res.json({
          status: "0",
          msg: "suc"
        })
      }
    }
  })

})
router.post("/cartDel", function (req, res, next) {
  let userId = req.cookies.userId;
  let productId = req.body.productId;
  // let productNum = req.body.productNum;
  User.update({
    'userId': userId,
  }, {
    $pull: {
      "cartList":{
        "productid": productId
      }
    }
  },function(err,doc) {  
    if(err){
      res.json({
        status:"1",
        msg:err.message
      });
    }else{
      if(doc){
        // doc.cartList.
        res.json({
          status: "0",
          msg: "success"
        });
      }
    }
  })


})
router.post("/delAddress",function (req,res,next) {
  let userId = req.cookies.userId;
  let addressId = req.body.addressId;
  User.update({ 
    'userId': userId,
  },{
    $pull:{
      'addressList':{
        // 'addressId': addressId
        "_id": addressId
      }
    }
  },function (err,doc) {
    if(err){
      res.json({
        status:"1",
        msg:err.message
      })
    }else{
      if (doc && doc.nModified){
        res.json({
          status: "0",
          msg: "suc"
        })
      }else{
        res.json({
          status: "1",
          msg: "删除失败"
        })
      }
    }
  })
})
router.post("/addressList", function (req, res, next) {
  let userId = req.cookies.userId;
  let goodsModel = User.find({ userId: userId});
  goodsModel.exec(function (err, doc) {
    if(err){
      res.json({
        status:"1",
        msg:err.message
      })
    } else {
      if (doc.length>0){
        res.json({
          status: '0',
          msg: '',
          result: doc[0].addressList
        });
      }
    }
  })
})
router.post("/addAR", function (req, res, next) {
  let addressInfo = {
    userName : req.body.userName,
    streetName : req.body.streetName,
    postCode : req.body.postCode,
    tel : req.body.tel,
    addressId : "00000001"
  }
  let userId = req.cookies.userId;

  User.findOne({ userId: userId },function (err,userdoc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message
      })
    } else {
      if (userdoc) {
        userdoc.addressList.push(addressInfo);
        userdoc.save(function (err2,userdoc2) {
          if (err2) {
            res.json({
              status: "1",
              msg: err2.message
            })
          } else {
            res.json({
              status: '0',
              msg: '',
              result: 'suc'
            })
          }
        })
      }
    }
  });
})
router.post("/payMent",function (req,res,next) {
  let addressId = req.body.addressId,
      userId = req.cookies.userId,
      orderTotal = req.body.orderTotal;
    User.findOne({userId:userId},function (err,userdoc) {
      if(err){
        res.json({
          status:"0",
          msg:err.message
        })
      }else{
        let address = {},
            goodsList = [];
        userdoc.addressList.forEach(element => {
          if (addressId == element._id){
            address = element;
          }
        });
        userdoc.cartList.filter((element)=>{
          if(element.checked == '1'){
            goodsList.push(element)
          } 
        })


        let platNo = "141";
        let r1 = Math.floor(Math.random() * 10) //0~9
        let r2 = Math.floor(Math.random() * 10) 
        let sysDate = new Date().Format("yyyyMMddhhmmss");
        let createDate = new Date().Format("yyyy-MM-dd hh:mm:ss");
        let orderId = platNo + r1 + sysDate + r2;
        let order = {
          orderId : orderId,
          orderTotal:orderTotal,
          addressInfo: address,
          goodsList: goodsList,
          orderStatus: 1,
          createDate: createDate
        }
        userdoc.orderList.push(order);
        userdoc.save(function (err1, doc1) {
          if (err1) {
            res.json({
              status: "1",
              msg: err1.message,
              result: ''
            });
          } else {
            User.update({
              'userId': userId,
            }, {
                $pull: {
                  'cartList': {
                    "checked": 1
                  }
                }
              }, function (err3, doc3) {
                if(err3){
                  res.json({
                    status:"1",
                    msg:err3.message
                  })
                }else{
                  res.json({
                    status: "0",
                    msg: '',
                    result: {
                      orderId: order.orderId,
                      orderTotal: order.orderTotal
                    }
                  });
                }
            })
          }
        });

      }
    })


})
router.post("/orderDetail",function (req,res,next) {
  let orderId = req.body.orderId,
      userId = req.cookies.userId;

  User.findOne({userId:userId},function (err,userdoc) {
    if(err){
      res.json({
        status:"1",
        msg:err.message
      })
    }else{
      let orderInfo;
      userdoc.orderList.forEach(element => {
        if (element.orderId == orderId){
          orderInfo = element;
          // break;
        }
      });
      res.json({
        status: "0",
        msg: "suc",
        result:{
          "orderId": orderId,
          "orderTotal": orderInfo.orderTotal
        }
      })
    }
  })
})
router.post("/checkLogin",function (req,res,next) {
  let userName = req.cookies.userName;
  if(userName){
    res.json({
      status:"0",
      result:userName
    })
  }else{
    res.json({
      status: "1",
      msg:"未登录",
      result: ""
    })
  }
})
router.post("/getCartCount",function(req,res,next) {
  let userId = req.cookies.userId;
  User.findOne({ "userId": userId},function (err,userDoc) {
      if(err){
        res.json({
          "status": "1",
          "msg": err.message
        })
      } else {
        if(userDoc){
          let carTotalNum = 0;
          userDoc.cartList.forEach(element=>{
            carTotalNum += element.productNum;
          })
          res.json({
            status:"0",
            msg:"",
            result:{
              cartNum: carTotalNum
            } 
          })
        }
      }
  })
})
module.exports = router;
